package com.delivery.activity;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.delivery.adapter.PicturesAdapter;
import com.delivery.common.BaseActivity;
import com.delivery.common.MyProgressHandler;
import com.delivery.common.PageControlView;
import com.delivery.common.ScrollLayout;
import com.delivery.common.ShareWeibo;
import com.delivery.common.ScrollLayout.OnScreenChangeListenerDataLoad;
import com.delivery.module.CategoriesContent;
import com.delivery.module.ConfigModule;
import com.delivery.service.ICategoriesContent;
import com.delivery.service.impl.CategoriesContentService;
import com.delivery.utils.StringUtils;

import android.content.Context;
import android.os.Bundle; 
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;

 
public class PicturesActivity extends BaseActivity{ 
	
	private String TAG = "PicturesActivity";
	
	private ScrollLayout mScrollLayout;
	
	public static final int APP_PAGE_SIZE = 2;
	
	private Context mContext;
	
	private PageControlView pageControl;
	
	public static MyHandler myHandler;
	
	public int n=0;
	
	private DataLoading dataLoad;
   
	private static int currentIndex = 0;
	
	private static String categoriesId = "1";
	
	private static String typeId = "1";
	
	private static int totalCount;
	
	private static List<CategoriesContent> lists = new ArrayList<CategoriesContent>();
	
	private static StringBuffer params = new StringBuffer();
	
	private ICategoriesContent categoriesContentService = new CategoriesContentService();
	
	private  Button bt_jszp,bt_fgzp,bt_rxzp,bt_stzp;
	
	private MyProgressHandler myProgress;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mContext = this;
		setContentView(R.layout.mryt_item);
		dataLoad = new DataLoading();
		mScrollLayout = (ScrollLayout)findViewById(R.id.ScrollLayoutTest);
		typeId = getResources().getString(R.categories.type_mtyt);
		categoriesId= String.valueOf(R.categories.cate_jnzp);
		currentIndex = 0;
		
		myProgress = new MyProgressHandler(this,1);
		MyProgressThread my = new MyProgressThread();
		new Thread(my).start();
		
		myHandler = new MyHandler(this,1);
		bt_jszp = (Button) findViewById(R.id.bt_jszp);
		bt_fgzp = (Button) findViewById(R.id.bt_fgzp);
		bt_rxzp = (Button) findViewById(R.id.bt_rxzp);
		bt_stzp = (Button) findViewById(R.id.bt_stzp);
		bt_jszp.setOnClickListener(new TagQuery(R.categories.cate_jnzp));
		bt_fgzp.setOnClickListener(new TagQuery(R.categories.cate_fgzp));
		bt_rxzp.setOnClickListener(new TagQuery(R.categories.cate_rxzp));
		bt_stzp.setOnClickListener(new TagQuery(R.categories.cate_stzp));
	} 
	
	class TagQuery implements OnClickListener{
		
		private int categoriesId;
		
		public TagQuery(int categoriesId){
			this.categoriesId = categoriesId;
		}

		public void onClick(View v) {
			sendProgressMsg("2");
			Message msg = new Message();
			Bundle b = new Bundle();// 存放数据
			b.putString("rmsg", "1");
			b.putString("tab", "tab");
			b.putString("categoriesId", String.valueOf(categoriesId));
			msg.setData(b);
			PicturesActivity.myHandler.sendMessage(msg);
		}
		
	}

	/**
	 * gridView 的onItemLick响应事件
	 */
	public OnItemClickListener listener = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			System.out.println("position=----------------------"+position);
		}
		
	};
	
	@Override
	protected void onDestroy() {
		android.os.Process.killProcess(android.os.Process.myPid());
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	class MyProgressThread implements Runnable{

		public void run() {
			try {
				Thread.sleep(REST_TIME);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			sendProgressMsg("0");
			//起一个线程更新数据
			MyThread m = new MyThread();
			new Thread(m).start();
		}
		
	}
	
	public void sendProgressMsg(String rmsg){
		if(myProgress!=null){
			Message msg = new Message();
			Bundle b = new Bundle();// 存放数据
			b.putString("rmsg", rmsg);
			msg.setData(b);
			myProgress.sendMessage(msg); // 向Handler发送消息,更新UI
		}
	}
	
	// 更新后台数据
	class MyThread implements Runnable {
		public void run() {
			try {
				Thread.sleep(REST_TIME);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			String msglist = "1";
			Message msg = new Message();
			Bundle b = new Bundle();// 存放数据
			b.putString("rmsg", msglist);
			b.putString("categoriesId", categoriesId);
			b.putString("tab", "");
			msg.setData(b);
			myHandler.sendMessage(msg); // 向Handler发送消息,更新UI

		}
	}

	public class MyHandler extends Handler {
		private PicturesActivity mContext;
		public MyHandler(Context conn,int a) {
			mContext = (PicturesActivity)conn;
		}

		public MyHandler(Looper L) {
			super(L);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle b = msg.getData();
			String rmsg = b.getString("rmsg");
			if ("1".equals(rmsg)) {
				try{
					
					if(StringUtils.isNotEmpty(b.getString("tab")) && mScrollLayout!=null){
						currentIndex = 0;
						lists.clear();
						mScrollLayout.removeAllViews();
					}
					if(isNeedQueryData()){
						categoriesId = b.getString("categoriesId");
						String json = getCategoriesContentJson();
						if(StringUtils.isEmpty(json)){
							return;
						}
						
						JSONObject jsonObject = new  JSONObject(json);
						String 	total = jsonObject.getString("total");
						CategoriesContent categoriesContent = null;
						if(StringUtils.isEmpty(total) || Integer.parseInt(total) <=0){
							lists.add(null);
							GridView appPage = new GridView(mContext);
							appPage.setAdapter(new PicturesAdapter(mContext, lists, 0));
							mScrollLayout.addView(appPage);
							sendProgressMsg("1");
							return;
						}
						
						totalCount = Integer.parseInt(total);
						JSONArray jsonArray = jsonObject.getJSONArray("results");
						for (int i = 0; i < jsonArray.length(); i++) {
							JSONObject jb = jsonArray.getJSONObject(i);
							if(jb != null){
								categoriesContent = new CategoriesContent();
								categoriesContent.setContentDesc(jb.getString("contentDesc"));
								categoriesContent.setImgUrl(jb.getString("imgUrl"));
								categoriesContent.setShareAddress(jb.getString("shareAddress"));
								categoriesContent.setUpdateTime(jb.getString("updateTime"));
								lists.add(categoriesContent);
							}
						}
				
						int endPage =  (currentIndex <=0 ? 1 : currentIndex+1) * APP_PAGE_SIZE;
						int beginPage = endPage - APP_PAGE_SIZE;
						if(endPage > totalCount){
							endPage = totalCount;
						}
						for (int i = beginPage; i < endPage; i++) {
							GridView appPage = new GridView(mContext);
							// get the "i" page data
							appPage.setAdapter(new PicturesAdapter(mContext, lists, i));
							appPage.setNumColumns(1);
							appPage.setOnItemClickListener(listener);
							
							mScrollLayout.addView(appPage);
							
						}
						mScrollLayout.setPageSize(APP_PAGE_SIZE);
						mScrollLayout.setTotalCount(totalCount);
						//加载分页
						pageControl = (PageControlView) findViewById(R.id.pageControl);
						pageControl.bindScrollViewGroup(mScrollLayout,totalCount);
						//加载分页数据
						dataLoad.bindScrollViewGroup(mScrollLayout);
					}
					sendProgressMsg("1");
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private boolean isNeedQueryData(){
		if(lists!=null && (lists.size() <=0 || lists.size() < totalCount)) 
		return true;
		return false;
	}
	
	/**
	 * 获取远程服务器数据，返回格式是json
	 * @return
	 */
	public String getCategoriesContentJson(){
		params.delete(0, params.length());
		params.append(ConfigModule.GET_CATEGORIESCONTENT_URL);
		params.append("&pageSize="+APP_PAGE_SIZE);
		params.append("&typeId="+typeId);
		params.append("&categoriesId="+getCategoriesId());
		params.append("&currentPage="+currentIndex);
		params.append("&type=level1");
		System.out.println(params);
	     try {
	    	 return  this.categoriesContentService.getCategoriesContents(String.valueOf(params));
		 } catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "query categoriesContentService is fail.");
			return "";
		 }
	}
	
	private String getCategoriesId(){
		if(StringUtils.isEmpty(categoriesId) || categoriesId.equals("0")){
			return "";
		}
		return getResources().getString(Integer.parseInt(categoriesId));
	}
	
	//分页数据
	class DataLoading {
		public void bindScrollViewGroup(ScrollLayout scrollViewGroup) {
			scrollViewGroup.setOnScreenChangeListenerDataLoad(new OnScreenChangeListenerDataLoad() {
				public void onScreenChange(int index) {
					currentIndex = index;
					generatePageControl();
				}
			});
		}
		
		private void generatePageControl(){
			MyThread m = new MyThread();
			new Thread(m).start();
		}
	}
	class Share implements OnClickListener{
		
		private String imgUrl;
		
		public Share(String imgUrl){
			this.imgUrl = imgUrl;
		}
		
		public void onClick(View v) {
			String result = ShareWeibo.shareContent(imgUrl);
			try {
				if(StringUtils.isEmpty(result)){
					return;
				}
				JSONObject jsonObject = new JSONObject(result);
				if(jsonObject!=null && StringUtils.isNotEmpty(jsonObject.getString("type"))){
					if(jsonObject.getString("type").equals("success")){
						//StringUtils.ToskShow(PicturesAdapter.this, String.valueOf(jsonObject.getString("msg")));
					}else{
						
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
		}
		
	}

}
